package com.kotlin.novel.ui

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.kotlin.novel.R
import com.kotlin.novel.adapter.TypesAdapter
import com.kotlin.novel.base.BaseFragment
import com.kotlin.novel.listener.OnItemViewClickListener
import com.kotlin.novel.model.TypeModel
import com.kotlin.novel.utils.HttpUtil
import kotlinx.android.synthetic.main.fragment_square.*
import kotlinx.android.synthetic.main.fragment_square.refresh_layout
import kotlinx.android.synthetic.main.search_view.*
import kotlinx.android.synthetic.main.type_gender.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import org.json.JSONObject


class SquareFragment private constructor() : BaseFragment(), View.OnClickListener, OnItemViewClickListener<TypeModel>, SwipeRefreshLayout.OnRefreshListener {
    private val typeModels = ArrayList<TypeModel>()
    private lateinit var typesAdapter: TypesAdapter
    private var gender="male"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)


    }
    companion object {
        val instance: SquareFragment by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
            SquareFragment()
        }
    }


    override fun getLayoutResId(): Int {
        return R.layout.fragment_square
    }

    override fun initView() {
        rv_types.layoutManager = LinearLayoutManager(activity)
        tv_search.setOnClickListener(this)
        tv_type_male.setOnClickListener(this)
        tv_type_female.setOnClickListener(this)
        refresh_layout.setColorSchemeResources(R.color.zhuti)
        refresh_layout.setOnRefreshListener(this)
        typesAdapter = TypesAdapter(activity as Context, typeModels)
        rv_types.adapter = typesAdapter
        typesAdapter.onItemViewClickListener = this
    }

    override fun initData() {
        requestData()
    }

    private fun requestData(refresh: Boolean = false,gender:String="male") = GlobalScope.launch(Dispatchers.Main){

        Log.d("test","")
        val http = HttpUtil()
        //不能在UI线程进行请求，使用async起到后台线程，使用await获取结果
        typeModels.clear()
        async(Dispatchers.Default) { http.httpGET1("http://api.zhuishushenqi.com/cats/lv2/statistics") }.await()
                .let {
                    val obj=JSONObject(it)

                    val typeList=obj.getJSONArray(gender)
                    for (i in 0 until typeList.length()) {
                        val typeModel=TypeModel()
                        val item=typeList.getJSONObject(i)

                        typeModel.name=item.getString("name")
                        typeModel.bookCount=item.getString("bookCount")
                        typeModel.monthlyCount=item.getString("monthlyCount")
                        typeModels.add(typeModel)
                    }
                    typesAdapter.notifyDataSetChanged()
                    refresh_layout.isRefreshing = false
                }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tv_search -> {
                startActivity(Intent(activity, SearchActivity::class.java))
            }
            R.id.tv_type_male->{
                Log.d("male type","ok")
                gender="male"
                typeModels.clear()
                typesAdapter.notifyDataSetChanged()
                requestData(false,gender)
            }
            R.id.tv_type_female->{
                gender="female"
                typeModels.clear()
                typesAdapter.notifyDataSetChanged()
                requestData(false,gender)
            }

        }
    }

    //item点击监听
    override fun itemClick(view: View, t: TypeModel) {
        when (view.id) {
            R.id.tv_item_type -> {
                startActivity(Intent(activity as Context, BookTypeActivity::class.java)
                        .putExtra("type", t.name)
                        .putExtra("typeUrl","")
                        .putExtra("monthRank",t.monthRank)
                        .putExtra("totalRank",t.totalRank)
                        .putExtra("gender",gender))
            }
        }
    }

    override fun onRefresh() {
        //refresh_layout.isRefreshing = false
        typeModels.clear()
        typesAdapter.notifyDataSetChanged()
        requestData(true,gender)
    }

}